package com.mywork.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.NewActionHelp;
import com.ciko.code.adapter.ContactGroupAdapter;
import com.ciko.code.base.BaseActicity;
import com.ciko.code.logic.bean.AddressBookInfo;
import com.ciko.code.logic.bean.ContractBean;
import com.ciko.code.logic.bean.SuperBean;
import com.ciko.code.logic.dao.ApproverBookInfoDao;
import com.ciko.code.logic.dao.SuperDao;
import com.ciko.code.utils.PerferencesUtil;
import com.ciko.code.utils.Utils;
import com.google.gson.reflect.TypeToken;
import com.mywork.R;
import com.mywork.WorkUIKit;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.ui.widget.MyExpandableListView;
import com.ui.widget.refresh.base.PullToRefreshBase;
import com.ui.widget.refresh.base.PullToRefreshBase.OnRefreshListener;
import com.ui.widget.refresh.internal.PullToRefreshScrollView;
import com.ui.widget.refresh.internal.PullToRefreshUtil;

import org.apache.http.Header;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

public class ApproverActivity extends BaseActicity implements OnClickListener {
    public static int[] isClose;
    private PullToRefreshScrollView contentView;
    private MyExpandableListView listView;
    private TextView tvSearch;
    private List<SuperBean> groups = new ArrayList<>();
    private HashMap<String, List<AddressBookInfo>> contacts = new HashMap<>();
    private ProgressDialog progressDialog;
    private static final int PROGRESS_SHOW = 111;
    private static final int PROGRESS_HIDE = 112;
    private static final int REFRESH_DATA = 113;
    private static final int SEARCH_DATA = 114;
    private Context context;

    private ContactGroupAdapter adapter;
    //数据库相关
    private SuperDao groupDao;
    private ApproverBookInfoDao addressBookInfoDao;
    /**
     * 是否在搜索框
     */
    private boolean isSearch = false;
    private EditText et_approver_search;
    private LinearLayout ll_find;
    private TextView tv_cancel;
    private RelativeLayout approver_nav;
    private long lastTimeStamp;
    private TextView no_approver;
    private Button search_bt_delete;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case PROGRESS_SHOW:
                    progressDialog = ProgressDialog.show(context, "", "正在初始化...");
                    break;
                case PROGRESS_HIDE:
                    progressDialog.dismiss();
                    break;
                case REFRESH_DATA:
                    getDataFromDb();
                    showData();
                    break;
                case SEARCH_DATA://搜索
                    getSearchDb();
                    showData();
                    break;
            }
        }
    };


    private PerferencesUtil utils;
    /**
     * 是否发起人
     */
    private boolean isOrganiser;
    /**
     * 发起人用户id
     */
    private String userId;

    @Override
    protected void initTopBar() {
        enableNavRightIv("取消");
        setTitle("选择审批人");
        isOrganiser = getIntent().getBooleanExtra("isOrganiser", true);
        userId = getIntent().getIntExtra("userId", 0) + "";
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.approver_activity);
        context = this;
    }

    @Override
    protected void initView() {
        contentView = (PullToRefreshScrollView) findViewById(R.id.approver_psview);
        PullToRefreshUtil.initLabel(this, contentView);
        tvSearch = (TextView) findViewById(R.id.et_contact_search);
        listView = (MyExpandableListView) findViewById(R.id.contacts_list);
        et_approver_search = (EditText) findViewById(R.id.et_approver_search);
        ll_find = (LinearLayout) findViewById(R.id.ll_find);
        tv_cancel = (TextView) findViewById(R.id.tv_cancel);
        no_approver = (TextView) findViewById(R.id.no_approver);
        search_bt_delete = (Button) findViewById(R.id.search_bt_delete);

        approver_nav = (RelativeLayout) findViewById(R.id.common_nav);
    }

    @Override
    protected void initAdapter() {
    }

    @Override
    protected void initDates() {
        groupDao = SuperDao.getInstance(context);
        addressBookInfoDao = ApproverBookInfoDao.getInstance(context);

        utils = PerferencesUtil.getInstance(context);
        String userId = WorkUIKit.getUserId();
        if (!utils.getLastLoginUser().equals(userId)) {//判断是否是同一用户,切换用户删除数据库
            groupDao.deleteAll();
            addressBookInfoDao.deleteAll();
            utils.clearAllData();
            utils.setLastLoginUser(userId);
        }
        lastTimeStamp = utils.getApproveContactLastTimeStamp();
        NewActionHelp.qryEnterpriseAddressBookList(context, lastTimeStamp, "y", new GetAddressBookListHandler());
    }

    @Override
    protected void initListener() {
        tvSearch.setOnClickListener(this);
        tv_cancel.setOnClickListener(this);
        search_bt_delete.setOnClickListener(this);
        //搜索
        et_approver_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                handler.sendEmptyMessage(SEARCH_DATA);
                //隐藏键盘
                Utils.hideInputMethodManager(context, et_approver_search);
                return true;
            }
        });
        contentView.setOnRefreshListener(new OnRefreshListener<ScrollView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
                Utils.hideInputMethodManager(context, et_approver_search);
                if (contentView.isHeaderShown()) {
                    refrush();
                } else if (contentView.isFooterShown()) {
                    boolean isAllClose = true;
                    int i;
                    for (i = 0; i < isClose.length; i++) {
                        if (isClose[i] == 1) {
                            isAllClose = false;
                            break;
                        }
                    }
                    if (!isAllClose) {
                        SuperBean group = groups.get(i);
                        List<AddressBookInfo> list = contacts.get(group.getName());
                        if (list.size() < group.getAddressBookList().size()) {
                            int size = list.size();
                            for (int j = list.size(); j < group.getAddressBookList().size() && j < size + 50; j++) {
                                list.add(group.getAddressBookList().get(j));
                            }
                            contacts.put(group.getName(), list);
                            adapter.notifyDataSetChanged();
                        }
                    }
                    contentView.onRefreshComplete();
                }
            }
        });
        //监听搜索框内容变化
        et_approver_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {//输入文字之前的状态
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {//输入过程中的状态
            }

            @Override
            public void afterTextChanged(Editable s) {//输入结束后的状态
                if (et_approver_search.getText().toString().isEmpty()) {
                    search_bt_delete.setVisibility(View.GONE);
                } else {
                    search_bt_delete.setVisibility(View.VISIBLE);
                }
            }
        });

        //取消退出界面
        setOnNavRightClickListener(new OnNavRightClickListener() {
            @Override
            public void onNavRightClick() {
                ApproverActivity.this.finish();
            }
        });
    }

    /**
     * 组内排序
     */
    private void sortContacts() {
        List<AddressBookInfo> contacts;
        AddressBookInfo contact;
        for (SuperBean group : groups) {
            contacts = group.getAddressBookList();
            for (int i = 0; i < contacts.size() - 1; i++) {
                for (int j = i; j < contacts.size(); j++) {
                    if (contacts.get(i).getSortNum() > contacts.get(j).getSortNum()) {
                        contact = contacts.get(i);
                        contacts.set(i, contacts.get(j));
                        contacts.set(j, contact);
                    }
                }
            }
            group.setAddressBookList(contacts);
        }
    }

    /**
     * 组排序
     */
    private void sortGroups() {
        SuperBean bean;
        for (int i = 0; i < groups.size() - 1; i++) {
            for (int j = i + 1; j < groups.size(); j++) {
                if (groups.get(i).getSortNum() < groups.get(j).getSortNum()) {
                    bean = groups.get(i);
                    groups.set(i, groups.get(j));
                    groups.set(j, bean);
                }
            }
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == tvSearch) {
            isSearch();
            //获取焦点并弹出输入法
            et_approver_search.setFocusableInTouchMode(true);
            et_approver_search.requestFocus();
            Utils.showInputMethodManager(context);
        } else if (v == tv_cancel) {
            Utils.hideInputMethodManager(context, et_approver_search);
            isSearch();
        } else if (v == search_bt_delete) {
            search_bt_delete.setVisibility(View.GONE);
            et_approver_search.setText("");
            handler.sendEmptyMessage(REFRESH_DATA);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && isSearch) {
            isSearch();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 设置搜索栏显示隐藏
     */
    private void isSearch() {
        approver_nav.setVisibility(isSearch ? View.VISIBLE : View.GONE);
        tvSearch.setVisibility(isSearch ? View.VISIBLE : View.GONE);
        ll_find.setVisibility(isSearch ? View.GONE : View.VISIBLE);
        if (isSearch) {
            et_approver_search.setText("");
            handler.sendEmptyMessage(REFRESH_DATA);
        }
        isSearch = !isSearch;
    }

    /**
     * 下拉刷新
     */
    private void refrush() {
        listView.setVisibility(View.GONE);
        initDates();
    }

    public class GetAddressBookListHandler extends ObjectHttpResponseHandler<ContractBean> {
        @Override
        public Type getType() {
            return new TypeToken<ContractBean>() {
            }.getType();
        }

        @Override
        public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
            if (!"".equals(et_approver_search.getText().toString())) {
                handler.sendEmptyMessage(REFRESH_DATA);
            } else {
                handler.sendEmptyMessage(SEARCH_DATA);
            }
        }

        @Override
        public void onSuccess(final int arg0, Header[] arg1, final ContractBean arg2, String arg3) {
            lastTimeStamp = arg2.getLastTimeStamp();
            utils.setApproveContactLastTimeStamp(lastTimeStamp);
            if (arg2.getGroupList() != null && arg2.getGroupList().size() > 0) {
                new Thread() {
                    @Override
                    public void run() {
                        groups = arg2.getGroupList();
                        putDataToDB();
                    }
                }.start();
            } else {
                if (!"".equals(et_approver_search.getText().toString())) {
                    handler.sendEmptyMessage(SEARCH_DATA);
                } else {
                    handler.sendEmptyMessage(REFRESH_DATA);
                }
            }
        }
    }

    /**
     * 数据库存储
     */
    private void putDataToDB() {
        handler.sendEmptyMessage(PROGRESS_SHOW);
        for (SuperBean group : groups) {
            if (groupDao.getById(group.getGroupId()) != null) {
                groupDao.update(group);
            } else {
                groupDao.add(group);
            }
            for (AddressBookInfo addressBookInfo : group.getAddressBookList()) {
                if (addressBookInfoDao.getById(addressBookInfo.getContactId(), group.getGroupId()) != null) {
                    addressBookInfoDao.update(addressBookInfo);
                } else {
                    addressBookInfoDao.add(addressBookInfo);
                }
            }
        }
        handler.sendEmptyMessage(PROGRESS_HIDE);
        if (!"".equals(et_approver_search.getText().toString())) {
            handler.sendEmptyMessage(SEARCH_DATA);
        } else {
            handler.sendEmptyMessage(REFRESH_DATA);
        }
    }

    /**
     * 查询所有
     */
    private void getDataFromDb() {
        groups.clear();
        List<SuperBean> dbGroups = groupDao.getAll();
        if (isOrganiser) {//是否发起人
            for (int i = 0; i < dbGroups.size(); i++) {
                List<AddressBookInfo> addressBookList = new ArrayList<>();
                List<AddressBookInfo> dbList = addressBookInfoDao.getListByGroupId(dbGroups.get(i).getGroupId());
                for (AddressBookInfo info : dbList) {
                    if (info.getIsDelete().equals("n")) {
                        addressBookList.add(info);
                    }
                }
                dbGroups.get(i).setAddressBookList(addressBookList);
            }
        } else {
            for (int i = 0; i < dbGroups.size(); i++) {
                List<AddressBookInfo> addressBookList = new ArrayList<>();
                List<AddressBookInfo> dbList = addressBookInfoDao.getListByGroupId(dbGroups.get(i).getGroupId());
                for (AddressBookInfo info : dbList) {
                    if (info.getIsDelete().equals("n") && !TextUtils.equals(info.getUserId(), userId)) {
                        addressBookList.add(info);
                    }
                }
                dbGroups.get(i).setAddressBookList(addressBookList);
            }
        }
        for (SuperBean group : dbGroups) {
            if (group.getAddressBookList() != null && group.getAddressBookList().size() != 0) {
                groups.add(group);
            }
        }
    }

    /**
     * 搜索查询
     */
    private void getSearchDb() {
        groups.clear();
        List<SuperBean> dbGroups = groupDao.getAll();
        String condition = et_approver_search.getText().toString().trim();
        List<AddressBookInfo> dbList = new ArrayList<>();
        if (addressBookInfoDao.search(condition) != null) {//人名查询
            dbList.addAll(addressBookInfoDao.search(condition));
        }
        if (addressBookInfoDao.searchByPhone(condition) != null && !condition.isEmpty()) {//电话号码查询
            dbList.addAll(addressBookInfoDao.searchByPhone(condition));
        }
        if (isOrganiser) {//是否发起人
            for (int i = 0; i < dbGroups.size(); i++) {
                List<AddressBookInfo> addressBookList = new ArrayList<>();
                for (AddressBookInfo info : dbList) {
                    if (info.getIsDelete().equals("n") && info.getGroupId() == dbGroups.get(i).getGroupId()) {
                        addressBookList.add(info);
                    }
                }
                dbGroups.get(i).setAddressBookList(addressBookList);
            }
        } else {
            for (int i = 0; i < dbGroups.size(); i++) {
                List<AddressBookInfo> addressBookList = new ArrayList<>();
                for (AddressBookInfo info : dbList) {
                    if (info.getIsDelete().equals("n") && info.getGroupId() == dbGroups.get(i).getGroupId() && !TextUtils.equals(info.getUserId(), userId)) {
                        addressBookList.add(info);
                    }
                }
                dbGroups.get(i).setAddressBookList(addressBookList);
            }
        }
        for (SuperBean group : dbGroups) {//过滤空group
            if (group.getAddressBookList() != null && group.getAddressBookList().size() != 0) {
                groups.add(group);
            }
        }
    }

    private void showData() {
        sortGroups();
        sortContacts();
        int p = 0;
        isClose = new int[groups.size()];
        for (SuperBean group : groups) {
            List<AddressBookInfo> list = new ArrayList<>();
            if (group.getAddressBookList().size() > 50) {
                for (int i = 0; i < 50; i++) {
                    list.add(group.getAddressBookList().get(i));
                }
            } else {
                list.addAll(group.getAddressBookList());
            }
            contacts.put(group.getName(), list);
            isClose[p] = 0;
            p++;
        }
        Collections.reverse(groups);
        adapter = new ContactGroupAdapter(context, listView, groups, contacts);
        listView.setAdapter(adapter);
        listView.setGroupIndicator(null);
        listView.setFocusable(false);
        listView.setFocusableInTouchMode(false);
        contentView.onRefreshComplete();
        //若适配器中无数据隐藏布局
        if (groups == null || groups.size() == 0) {
            listView.setVisibility(View.GONE);
            no_approver.setVisibility(View.VISIBLE);
        } else {
            listView.setVisibility(View.VISIBLE);
            no_approver.setVisibility(View.GONE);
        }
    }
}
